﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

namespace Library1
{
    public class UpdateApplication 
    {
        ws_update.Update _wsUpdate = null;
        string _clientDirectoryPath = "";
        string _serverDirectoryName = "";
        

        public virtual string ClientDirectoryPath
        {
            get
            {             
                return _clientDirectoryPath;
            }
            set
            {
                _clientDirectoryPath = value;
            }
        }

        public virtual string ServerDirectoryName
        {
            get
            {
                return _serverDirectoryName;
            }
            set
            {
                _serverDirectoryName = value;
            }
        }

        public virtual List<ws_update.UpdateInfos> UpdateInfos
        {
            get
            {
                List<ws_update.UpdateInfos> updateInfos = new List<ws_update.UpdateInfos>();
                ws_update.UpdateInfos[] updateInfosArray = _wsUpdate.GetAllUpdateInfosCompressed(ServerDirectoryName);
                if (updateInfosArray != null)
                {
                    updateInfos.AddRange(_wsUpdate.GetAllUpdateInfosCompressed(ServerDirectoryName));
                }

                return updateInfos;
            }
        }
        

        public UpdateApplication()
        {
            _wsUpdate = new ws_update.Update();
            _wsUpdate.Timeout = (1000 * 60) * 15;
        }

        //public static void Download(string serverDirectoryName, string clientDirectoryPath)
        //{
        //    List<ws_update.UpdateInfos> source = new List<ws_update.UpdateInfos>();
        //    object[] os = _wsUpdate.GetAllUpdateInfosCompressed(serverDirectoryName);
        //    foreach (object o in os)
        //        source.Add((ws_update.UpdateInfos)o);

        //    string clientFilePath;
        //    foreach (ws_update.UpdateInfos ui in source)
        //    {
        //        clientFilePath = clientDirectoryPath + ui.filepath;
        //        if (!File.Exists(clientFilePath) || (File.GetLastWriteTimeUtc(clientFilePath) < ui.time.ToUniversalTime()))
        //        {
        //            ws_update.UpdateInfos severFileInfo = _wsUpdate.GetFileCompressed(serverDirectoryName, ui.filepath.Replace("\\", "/"));

        //            //we try to create the directory                    
        //            string directoryPathOfClientFile = clientFilePath.Replace(System.IO.Path.GetFileName(clientFilePath), "");
        //            try
        //            {
        //                Directory.CreateDirectory(directoryPathOfClientFile);
        //            }
        //            catch { }                    

        //            if (severFileInfo.bin != null && severFileInfo.bin.Length > 0)
        //            {
        //                FileStream fs2 = File.Create(clientFilePath);
        //                fs2.Write(severFileInfo.bin, 0, (int)severFileInfo.bin.Length);
        //                fs2.Close();
        //                File.SetLastWriteTimeUtc(clientFilePath, severFileInfo.time.ToUniversalTime());
        //            }
        //        }
        //    } 
        //}

        public virtual int GetNumberToUpdate()
        {            
            int total = 0;

            //List<ws_update.UpdateInfos> source = new List<ws_update.UpdateInfos>();            
            //source.AddRange(_wsUpdate.GetAllUpdateInfosCompressed(ServerDirectoryName));
            List<ws_update.UpdateInfos> source = UpdateInfos;
            string clientFilePath;
            foreach (ws_update.UpdateInfos ui in source)
            {
                clientFilePath = ClientDirectoryPath + ui.filepath;
                if (!File.Exists(clientFilePath) || File.GetLastWriteTimeUtc(clientFilePath) < ui.time.ToUniversalTime())
                {
                    total += 1;
                }
            }

            return total;
        }

        public virtual void Download()
        {
            List<ws_update.UpdateInfos> source = new List<ws_update.UpdateInfos>();
            source.AddRange(_wsUpdate.GetAllUpdateInfosCompressed(ServerDirectoryName));
            
            string clientFilePath;
            foreach (ws_update.UpdateInfos ui in source)
            {
                clientFilePath = ClientDirectoryPath + ui.filepath;
                if (!File.Exists(clientFilePath) || (File.GetLastWriteTimeUtc(clientFilePath) < ui.time.ToUniversalTime()))
                {
                    ws_update.UpdateInfos severFileInfo = _wsUpdate.GetFileCompressed(ServerDirectoryName, ui.filepath.Replace("\\", "/"));

                    //we try to create the directory                    
                    string directoryPathOfClientFile = clientFilePath.Replace(System.IO.Path.GetFileName(clientFilePath), "");
                    if (Directory.Exists(directoryPathOfClientFile) == false)
                    {
                        Directory.CreateDirectory(directoryPathOfClientFile);
                    }                   

                    if (severFileInfo.bin != null && severFileInfo.bin.Length > 0)
                    {
                        FileStream fs2 = File.Create(clientFilePath);
                        fs2.Write(severFileInfo.bin, 0, (int)severFileInfo.bin.Length);
                        fs2.Close();
                        File.SetLastWriteTimeUtc(clientFilePath, severFileInfo.time.ToUniversalTime());
                    }
                }
            }
        }

        public static void RunScripts(string directoryPath)
        {
            string[] files = Directory.GetFiles(directoryPath);

            foreach (string file in files)
            {
                RunScript(file);
            }
        }

        public static void RunScript(string filePath)
        {
            RunScript(".", filePath);
        }

        public static void RunScript(string serverInstance, string pathToScriptFile)
        {
            var serverConn = new ServerConnection();
            serverConn.ServerInstance = serverInstance;
            serverConn.LoginSecure = true;

            Server server = new Server(serverConn);
            FileInfo file = new FileInfo(pathToScriptFile);            
            string script = file.OpenText().ReadToEnd();            

            server.ConnectionContext.ExecuteNonQuery(script);
        }

    }
}
